package com.atlin.project.service.fm.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.atlin.project.model.fm.domain.StockIssuanceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * @author atlin
 * @description 获取数据
 * @createDate 2025/5/8 13:55
 */
@Slf4j
@Component
public class LoadData {

    /**
     * 获取待发转债数据
     */
    public static List<StockIssuanceInfo> loadCbData() {
        long s = System.currentTimeMillis();
        String path = "https://www.jisilu.cn/webapi/cb/pre/?history=N";
        HttpResponse response = null;
        try {
            response = HttpRequest.get(path).setConnectionTimeout(5000).execute();
        } catch (Exception e) {
            log.error("获取待发转债数据失败，请求发送失败。");
        }
        log.info("加载耗时：{} ms", (System.currentTimeMillis() - s));
        if (response != null && response.getStatus() == 200) {
            String body = response.body();

            JSONObject jsonData = JSONUtil.parseObj(body);
            JSONArray data = jsonData.getJSONArray("data");
            if (data != null) {
                List<StockIssuanceInfo> dataList = data.stream().map(item -> parseBondData((JSONObject) item)).collect(Collectors.toList());

                log.info("处理耗时：{} ms", (System.currentTimeMillis() - s));
                return dataList;
            }

        } else {
            log.error("获取待发转债数据失败！");
        }
        return new ArrayList<>(0);
    }

    private static StockIssuanceInfo parseBondData(JSONObject cell) {
        StockIssuanceInfo bond = new StockIssuanceInfo();
        // 基础信息
        bond.setStockCode(cell.getStr("stock_id"));
        bond.setStockName(cell.getStr("stock_nm"));
        bond.setBondCode(cell.getStr("bond_id"));
        bond.setBondName(cell.getStr("bond_nm"));

        // 价格信息
        bond.setStockPrice(cell.getBigDecimal("price"));
        bond.setIncreaseRate(cell.getBigDecimal("increase_rt"));
        bond.setConversionPrice(cell.getBigDecimal("convert_price"));

        // 发行信息
        bond.setIssuanceScale(cell.getBigDecimal("amount")); // amount对应issuanceScale
        bond.setOnlineScale(cell.getBigDecimal("online_amount"));
        bond.setPerHundredStock(cell.getBigDecimal("cb_amount"));

        // 日期信息
        bond.setProgressDate(parseDate(cell.getStr("progress_dt")));
        bond.setRecordDate(parseDate(cell.getStr("record_dt")));

        // 配售信息
        bond.setAllocationRate(cell.getBigDecimal("ration_rt"));
        bond.setAccountWinningRate(cell.getBigDecimal("lucky_draw_rt"));
        bond.setSubscriptionAccounts(cell.getInt("apply10")); // apply10对应subscriptionAccounts

        // 状态信息
        bond.setProgressStatus(cell.getStr("progress_nm"));
        bond.setBondType(cell.getStr("cb_type"));

        // 处理可能为null的BigDecimal字段
        safeSetBigDecimal(bond::setPerShareAllocation, cell.getStr("per_share_allocation"));
        safeSetBigDecimal(bond::setAllocationFor10, cell.getStr("allocation_for_10"));
        safeSetBigDecimal(bond::setUnderwritingRatio, cell.getStr("underwriter_rt"));

        return bond;
    }

    // 辅助方法：安全设置BigDecimal
    private static void safeSetBigDecimal(Consumer<BigDecimal> setter, String value) {
        if (value != null && !value.equalsIgnoreCase("null")) {
            setter.accept(new BigDecimal(value));
        }
    }

    // 辅助方法：日期解析
    private static Date parseDate(String dateStr) {
        if (dateStr == null || dateStr.isEmpty()) {
            return null;
        }
        try {
            return new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
        } catch (ParseException e) {
            log.warn("日期解析失败: {}", dateStr, e);
            return null;
        }
    }

    public static void main(String[] args) {
        loadCbData();
    }
}
